import 'dart:convert';
import 'package:http/http.dart' as http;
import '../model/api_response.dart';
import '../model/paged_response.dart';

class ParserUtils {
  // 通用解析方法 - 处理单个对象响应
  static ApiResponse<T> parseObjectResponse<T>(http.Response response, {
    required T Function(dynamic json) parser,
    String? dataKey, // 可选的数据键（如 "data"）
  }) {
    try {
      final jsonData = jsonDecode(response.body);
      // 提取实际数据（如果有嵌套结构）
      dynamic data = jsonData;
      if (dataKey != null && jsonData is Map) {
        data = jsonData[dataKey];
      }
      // 处理不同类型
      if (T == List) {
        if (data is List) {
          final list = data.map((item) => parser(item)).toList() as T;
          return ApiResponse<T>(
              data: list, status: response.statusCode, message: "success");
        } else {
          throw "Expected list but got ${data.runtimeType}";
        }
      } else {
        throw "Expected map but got ${data.runtimeType}";
      }
    } catch (e) {
      return ApiResponse<T>(
          data: null,
          status: response.statusCode,
          message: "JSON parsing error: $e\nResponse body: ${response.body}");
    }
  }

  // 通用解析方法 - 处理列表响应
  static ApiResponse<List<T>> parseListResponse<T>(http.Response response, {
    required T Function(Map<String, dynamic>) itemParser
  }) {
    try {
      final jsonData = jsonDecode(response.body);
      if (jsonData is List) {
        final data = jsonData.map((item) =>
            itemParser(item as Map<String, dynamic>)).toList();
        return ApiResponse(data: data, status: response.statusCode,
            message: "Success");
      } else {
        throw "Expected list but got ${jsonData.runtimeType}";
      }
    } catch (e) {
      return ApiResponse<List<T>>(
        data: null,
        status: response.statusCode,
        message: "JSON parsing error: $e\nResponse body: ${response.body}",
      );
    }
  }

// 处理分页响应
  static ApiResponse<PagedResponse<T>> parsePagedResponse<T>(
      http.Response response, {
        required T Function(dynamic json) itemParser,
        String? dataKey = "items",
        String? totalKey = "total",
        String? pageKey = "page",
        String? perPageKey = "perPage",
      }) {
    try {
      final jsonData = jsonDecode(response.body);
      final items = (jsonData[dataKey] as List).map(itemParser).toList();
      final total = jsonData[totalKey] as int;
      final page = jsonData[pageKey] as int;
      final perPage = jsonData[perPageKey] as int;
      return ApiResponse<PagedResponse<T>>(
          data: PagedResponse<T>(
              items: items, total: total, page: page, perPage: perPage),
          status: response.statusCode,
          message: "Success");
    } catch (e) {
      return ApiResponse<PagedResponse<T>>(
          data: null,
          status: response.statusCode,
          message: "Paged data parsing error: $e");
    }
  }

}

